package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.UserDao;
import com.foreknow.elm.dao.impl.UserDaoImpl;
import com.foreknow.elm.po.User;
import com.foreknow.elm.service.UserService;
import com.foreknow.elm.util.DBUtil;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    @Override
    public int saveUser(User user) {
        int result = 0;
        UserDao userDao = new UserDaoImpl();
        try {
            //开始事务
            DBUtil.beginTransaction();
            result = userDao.saveUser(user);
            //提交事务
            DBUtil.commitTransaction();
        }  catch (Exception e) {
            try {
                //取消之前的所有操作
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int getUserById(String userId) {
        int result = 0;
        UserDao userDao = new UserDaoImpl();
        try {
            result = userDao.getUserById(userId);
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public User getUserByIdByPass(String userId, String password) {
       User user = null;
        UserDao userDao = new UserDaoImpl();
        try {
            user = userDao.getUserByIdByPass(userId,password);
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            DBUtil.close();
        }
        return user;
    }
}
